package com.ks.common.handler;

import com.alibaba.fastjson.JSONException;
import com.ks.common.exception.BizException;
import com.ks.common.util.JsonData;
import lombok.extern.slf4j.Slf4j;
import org.redisson.client.RedisException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.FileNotFoundException;
import java.sql.SQLException;
import java.time.DateTimeException;

/**
 * 自定义异常处理程序
 *
 * @author KingAusten
 * @date 2022/08/17 18:03:03
 */
@ControllerAdvice
@Slf4j
public class CustomExceptionHandler{

    /**
     * @param e 异常
     *          <p>
     *          处理程序
     *
     * @return {@link JsonData }
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public JsonData handler(Exception e){

        if(e instanceof NullPointerException){
            log.error("[空指针异常]{ }",e);
            return JsonData.buildError("空指针异常");
        }
        if(e instanceof SQLException){
            log.error("[数据库异常]{ }",e);
            return JsonData.buildError("数据库异常");
        }
        if(e instanceof RedisException){
            log.error("[Redis异常]{ }",e);
            return JsonData.buildError("Redis异常");
        }
        if(e instanceof FileNotFoundException){
            log.error("[文件异常]{ }",e);
            return JsonData.buildError("文件异常");
        }
        if(e instanceof ClassNotFoundException){
            log.error("[类异常]{ }",e);
            return JsonData.buildError("类找不到异常");
        }
        if(e instanceof NumberFormatException){
            log.error("[数字异常]{ }",e);
            return JsonData.buildError("数字异常");
        }
        if(e instanceof ArithmeticException){
            log.error("[算术异常]{ }",e);
            return JsonData.buildError("算术异常");
        }
        if(e instanceof ArrayIndexOutOfBoundsException){
            log.error("[数组异常]{ }",e);
            return JsonData.buildError("数组异常");
        }
        if(e instanceof DateTimeException){
            log.error("[日期异常]{ }",e);
            return JsonData.buildError("日期异常");
        }
        if(e instanceof JSONException){
            log.error("[JSON异常]{ }",e);
            return JsonData.buildError("JSON异常");
        }
        if(e instanceof BizException){
            BizException bizException = (BizException)e;
            log.error("[业务异常]{ }",e);
            return JsonData.buildCodeAndMsg(bizException.getCode(),bizException.getMsg());
        }else{
            log.error("[系统异常]{ }",e);
            return JsonData.buildError("系统异常");
        }

    }

}
